<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd()"
                >新增角色</el-button
              >
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="hDel(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件
              current-change: 翻页时执行回调
              size-change: 每页几条 改变执行
              total： 一共有几条数据
              current-page： 当前的页码
              page-size： 每页显示几条
              page-sizes： 可以自己选择的 每页几条 数据
              layout： 整体的布局
              -->
              <el-pagination
                :page-sizes="[1, 2, 3, 4]"
                :current-page="page"
                :total="total"
                :page-size="pagesize"
                layout="sizes,prev,pager,next"
                @size-change="hSizeChange"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 新增弹框 -->
    <el-dialog
      :title="isEdit ? '编辑' : '添加'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hClose"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog = false">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit"
            >确定</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 分配权限的弹层 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showDialogAssign"
    >
      <AssignPermission v-if="showDialogAssign" @close="showDialogAssign=false" :roleId="roleId"/>
    </el-dialog>
  </div>
</template>
<script>
import { getRoles, deleteRole, addRole, updateRole } from "@/api/roles";
import AssignPermission from "./AssignPermission.vue";
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      isEdit: false,
      showDialog: false,
      pagesize: 2, //
      page: 1, // 页码
      total: 0, // 总条数
      roles: [],
      roleId: '',
      roleForm: {
        name: "",
        description: "",
      },
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "描述不能为空", trigger: "blur" },
        ],
      },
      showDialogAssign: false, // 分配权限对话框
    };
  },
  created() {
    this.loadRoles();
  },
  methods: {
    hAssign(id) {
      this.roleId = id
      this.showDialogAssign = true;
    },
    hClose() {
      // 重置表单
      this.roleForm = {
        // 表单数据项
        name: "",
        description: "",
      };
      this.$refs.roleForm.resetFields();
    },
    hAdd() {
      this.showDialog = true;
      this.isEdit = false;
    },
    hEdit(data) {
      console.log(data);
      this.showDialog = true;
      this.roleForm = { ...data };
      this.isEdit = true;
    },
    async doAdd() {
      // 1.发送请求
      await addRole(this.roleForm);
      // 2.重新加载数据
      // 进入到最后一页看刚才添加的数据数据
      // Math.ceil向上取整
      this.total++;
      this.page = Math.ceil(this.total / this.pagesize); // 最后一页
      this.loadRoles();
      // 3.提示成功
      this.$message.success("添加成功");
      // 4.弹窗关闭
      this.showDialog = false;
    },
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm);
        console.log(res);

        this.loadRoles();
        this.$message.success("编辑成功");
        this.showDialog = false;
      } catch (err) {
        this.$message.error("编辑失败");
        console.log(err);
      }
    },
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd();
        }
      });
    },
    async doDel(id) {
      try {
        const res = await deleteRole(id);
        // console.log(res);
        // 1. 提示
        this.$message.success("删除成功");
        // 2. 重新请求
        // 判断当前页面是否是最后一条数据&&页码>1
        // 删除了最后一条独立的数据(当前页只有这一条数据)
        if (this.roles.length === 1 && this.page > 1) {
          this.page--;
        }
        this.loadRoles();
      } catch (err) {
        console.log(err);
        this.$message.error("删除失败");
      }
    },
    hDel(id) {
      this.$confirm("确认删除吗?", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.doDel(id);
        })
        .catch(() => {});
    },
    hSizeChange(curPagesize) {
      console.log("curPagesize", curPagesize);
      // 1.更新参数
      this.pagesize = curPagesize;
      this.page = 1;
      // 2.重发请求
      this.loadRoles();
    },
    // 自动接收当前页码
    hCurrentChange(curPage) {
      console.log(curPage);
      // 1.更新页码
      this.page = curPage;
      // 2.重发请求
      this.loadRoles();
    },
    async loadRoles() {
      const res = await getRoles({ page: this.page, pagesize: this.pagesize });
      // console.log("res", res);
      this.total = res.data.total;
      this.roles = res.data.rows;
    },
  },
};
</script>
